package cn.yuanqiao.feignService.impl;

import cn.yuanqiao.common.constant.UserConstants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.core.domain.entity.SysDept;
import cn.yuanqiao.feignService.RemoteSysDeptService;
import cn.yuanqiao.system.service.ISysDeptService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @ProjectName: cn.yuanqiao.feignService.impl
 * @ClassName: RemoteSysDeptServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2024/7/23 13:42
 * @Version: 1.0
 **/
@Service
public class RemoteSysDeptServiceImpl implements RemoteSysDeptService {
    @Autowired
    private ISysDeptService deptService;

    @Override
    public R<SysDept> getInfoApi(Long deptId) {
        SysDept dept = deptService.selectDeptById(deptId);
        return R.ok(dept);
    }

    @Override
    public R<SysDept> addAsync(SysDept dept) {
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.fail("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        deptService.insertDept(dept);
        return R.ok(dept);
    }

    @Override
    public R<SysDept> getParentAsync(String deptName, String tenantCode) {
        SysDept dept = deptService.selectDeptByName(deptName, tenantCode);
        return R.ok(dept);
    }

    @Override
    public R<Integer> editAsync(SysDept dept) {
        Long deptId = dept.getDeptId();
        deptService.checkDeptDataScope(deptId);
        if (!deptService.checkDeptNameUnique(dept)) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } else if (dept.getParentId().equals(deptId)) {
            return R.fail("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (StringUtils.equals(UserConstants.DEPT_DISABLE, dept.getStatus()) && deptService.selectNormalChildrenDeptById(deptId) > 0) {
            return R.fail("该部门包含未停用的子部门！");
        }
        return R.ok(deptService.updateDept(dept));
    }

    @Override
    public R<Integer> removeAsync(Long deptId) {
        if (deptService.hasChildByDeptId(deptId)) {
            return R.fail("存在下级部门,不允许删除");
        }
        if (deptService.checkDeptExistUser(deptId)) {
            return R.fail("部门存在用户,不允许删除");
        }
        deptService.checkDeptDataScope(deptId);
        return R.ok(deptService.deleteDeptById(deptId));
    }

    @Override
    public R<List<SysDept>> getDeptListByDeptName(String deptName, String tenantCode) {
        SysDept sysDept = new SysDept();
        sysDept.setDeptName(deptName);
        sysDept.setTenantCode(tenantCode);
        return R.ok(deptService.selectDeptListByDeptName(sysDept));
    }
}
